#!/usr/env/bin python
# -*- coding: utf-8 -*-
import json

import mitmproxy.http
from mitmproxy import http, ctx


class Events:
    def http_connect(self, flow: mitmproxy.http.HTTPFlow):
        """
            An HTTP CONNECT request was received. Setting a non 2xx response on
            the flow will return the response to the client abort the
            connection. CONNECT requests and responses do not generate the usual
            HTTP handler events. CONNECT requests are only valid in regular and
            upstream proxy modes.
        """

    def requestheaders(self, flow: mitmproxy.http.HTTPFlow):
        """
            HTTP request headers were successfully read. At this point, the body
            is empty.
        """

    def request(self, flow: mitmproxy.http.HTTPFlow):
        """
            mitm实现Map Local
        """
        # if "quote.json" in flow.request.pretty_url:
        #     # 读取文件内容，然后构造一个http response
        #     with open('../resource/quote.json', encoding="utf-8") as f:
        #         flow.response = http.HTTPResponse.make(
        #             200,
        #             f.read(),
        #             {"content_type": "application/json"}
        #         )

    def responseheaders(self, flow: mitmproxy.http.HTTPFlow):
        """
            HTTP response headers were successfully read. At this point, the body
            is empty.
        """

    def response(self, flow: mitmproxy.http.HTTPFlow):
        """
            篡改http response中的部分字段内容，实现rewrite功能
        """
        if "quote.json" in flow.request.pretty_url and "x=" in flow.request.pretty_url:
            # 保存 服务器返回的响应数据 到本地文件
            with open('../resource/responese1.json', 'wb') as f:
                f.write(flow.response.content)

            # 取出response，转成字典格式,保存到res变量中
            res = json.loads(flow.response.content)

            # 读取参数文件到params中
            with open('../resource/params.txt', 'rb') as f:
                params = str(f.read()).split("'")[-2].split('\\n')
            ctx.log.info(f"{type(params)}, {params}")

            # 篡改res变量中的值
            count = 0
            for item in res['data']['items']:
                # 替换name，所有名称加上hogwards
                item['quote']['name'] += "hogwards"
                # 替换percent，涨跌幅替换为参数文件中的值
                if params[count]:
                    item['quote']['percent'] = params[count]
                count += 1

            # 将篡改后的res变量更新到response中
            flow.response.text = json.dumps(res)

            # 保存 篡改后的响应数据 到本地文件
            with open('../resource/responese2.json', 'wb') as f:
                f.write(flow.response.content)

    def error(self, flow: mitmproxy.http.HTTPFlow):
        """
            An HTTP error has occurred, e.g. invalid server responses, or
            interrupted connections. This is distinct from a valid server HTTP
            error response, which is simply a response with an HTTP error code.
        """


addons = [
    Events()
]